package com.hongxun.budget.ui.fragment.sg;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.fragment.BaseListFragment;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.DateUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.SgXUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.sg.CPBaseEntity;
import com.hongxun.net.SgProjectNet;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import dmax.dialog.SpotsDialog;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 在线施工项目列表
 */
public class OnlineProjectList extends BaseListFragment {
    private List<CPBaseEntity> datas = new ArrayList<>();
    private SuperAdapter<CPBaseEntity> superAdapter;

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return RecyclerViewUtils.getLinearLayoutManagerForVertical(context);
    }

    @Override
    public SuperAdapter getAdapter() {
        refresh.setEnabled(true);
        refresh.setRefreshing(true);
        superAdapter = new SuperAdapter<CPBaseEntity>(R.layout.sg_content_project) {

            @Override
            public void bindView(ViewHolder viewHolder, final CPBaseEntity entity, int i) {
                try {
                    ((TextView) viewHolder.getView(R.id.name)).setText(entity.getPBName());
                    ((TextView) viewHolder.getView(R.id.type)).setText(DBUtils.getBDataDictionaryEntity("progect_type", entity.getPBType()).getDValue());
                    ((TextView) viewHolder.getView(R.id.time)).setText(DateUtils.DateToString(entity.getPBAddtime()));
                    viewHolder.getView(R.id.refresh_btn).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            downLoadEntity(entity);
                        }
                    });
                } catch (NullPointerException e) {
                }
            }
        };
        superAdapter.setData(datas);
        superAdapter.setEmptyDataView(R.layout.view_empty);
        return superAdapter;
    }

    private void downLoadEntity(CPBaseEntity entity) {
        final SpotsDialog spotsDialog = new SpotsDialog(context, "正在缓存数据...");
        spotsDialog.show();
        Observable.just(entity).subscribeOn(Schedulers.io()).map(new Func1<CPBaseEntity, Long>() {
            @Override
            public Long call(CPBaseEntity entity) {
                DaoSession session = GreenDaoManager.getInstance().getmDaoSession();
                entity.setPBDatastate(SgStrKey.ytb);
                SPUtils.put(context, SgStrKey.uuidxm, entity.getGuid());
                return session.getCPBaseEntityDao().insertOrReplace(entity);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {
            @Override
            public void call(Long l) {
                spotsDialog.dismiss();
                spotsDialog.cancel();
                success(2, null);
            }
        });
    }

    @Override
    public void onRefresh() {
        SgProjectNet.getProject(context, this, 1);
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }

    @Override
    public void success(int i, JSONObject obj) {
        switch (i) {
            case 1:
                Observable.just(obj).subscribeOn(Schedulers.io()).map(new Func1<JSONObject, Boolean>() {
                    @Override
                    public Boolean call(JSONObject object) {
                        List<CPBaseEntity> list1 = JSON.parseArray(object.getString("cpBaseEntityList"), CPBaseEntity.class);
                        datas.clear();
                        for (CPBaseEntity entity : list1) {
                            if (!entity.getPBDatastate().equals(SgStrKey.del)) {
                                datas.add(entity);
                            }
                        }
//                        datas.addAll(list1);
                        List<CPBaseEntity> list2 = SgDBUtils.getCPBaseList(false);
                        for (CPBaseEntity entity : list2) {
                            boolean isDel = true;
                            for (CPBaseEntity baseEntity : datas) {
                                if (entity.getGuid().equals(baseEntity.getGuid())) {
                                    isDel = false;
                                    break;
                                }
                            }
                            if (isDel) {
                                entity.setPBDatastate(SgStrKey.del);
                                GreenDaoManager.getInstance().getmDaoSession()
                                        .getCPBaseEntityDao()
                                        .insertOrReplace(entity);
                            }
                        }
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean b) {
                        superAdapter.notifyDataSetChanged();
                        refresh.setRefreshing(false);
                    }
                });
                break;
            case 2:
                SgProjectNet.getProjectProgress(context, this, 3);
                break;
            case 3:
                SgXUtils.dealProjectProgress(context, obj, this, 4);
                break;
            case 4:
                T.showShort(context, "缓存成功");
                getActivity().finish();
                break;
        }
    }
}
